/*
 * ExternalSensor.cpp
 *
 *  Created on: Feb 2, 2009
 *      Author: Andrzej Olchawa
 *      mailto: andrzejolchawa@gmail.com
 *      http://www.hardtechnology.org
 *      This is a part of the Armazd project, which is covered by
 *      GNU GPL v2 license.
 */

#include "ExternalSensor.h"

ExternalSensor::ExternalSensor()
{
	sensorMessage = NULL;
	rawMessage = "sensor message new";
}

ExternalSensor::~ExternalSensor()
{
	if (rawMessage)
	{
		delete [] rawMessage;
	}

	if (sensorMessage)
	{
		delete sensorMessage;
	}
}

string ExternalSensor::executeCommand(string command)
{
	FILE *fpipe;
	char line[256];

	if ( !(fpipe = (FILE*)popen(command.c_str(),"r")) )
	{
		perror("Problems with pipe");
		return "";
	}

	string results = "";

	while ( fgets( line, sizeof line, fpipe))
	{
		results += string(line);
	}

	pclose(fpipe);

	return results;
}

char *ExternalSensor::generateRawMessage()
{
	HTProperties properties;

	string s = "";

	try
	{
		properties.loadProperties(COMMANDS_FILE_LIST);

		for (int i=0; i<properties.getNumberOfElements(); i++)
		{
			s += this->executeCommand(properties[i].value)+"\n";
		}

	}
	catch (HTException &e)
	{
		e.printException();
	}

	return (char*)s.c_str();
}

char *ExternalSensor::getRawMessage()
{
	char *s = this->generateRawMessage();
	return s;
}

SensorMessage *ExternalSensor::getSensorMessage()
{
	return sensorMessage;
}

extern "C" ExternalSensor* create()
{
    return new ExternalSensor();
}

extern "C" void destroy(ExternalSensor* p)
{
    delete p;
}
